package com.hc.server.actions;

import java.io.IOException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.hc.server.Error;
import com.hc.server.IAction;
import com.hc.server.Request;
import com.hc.server.Response;
import com.hc.server.conn.mall.MallResponse;
import com.hc.server.conn.mall.MallServerHelper;

public class GOODS_STATUS implements IAction {

	private static final String SN = "SN";
	
	@Override
	public void execute(Request req, Response resp) {
		String sn;
		try {
			sn = req.getStrArg(SN);
		} catch (JSONException e) {
			resp.setErrResp(Error.INVALID_ARGS_ERR_CD, Error.INVALID_ARGS_ERR_MSG);
			return;
		}
		
		MallResponse mResp = null;
		try{
			mResp = MallServerHelper.getStatus(sn);
		}catch (IOException e) {
			e.printStackTrace();
			resp.setErrResp(Error.MALLSERVER_NET_ERR_CD, Error.MALLSERVER_NET_ERR_MSG);
			return;
		} catch (JSONException e) {
			e.printStackTrace();
			resp.setErrResp(Error.MALLSERVER_DATA_FORMAT_ERR_CD, Error.MALLSERVER_DATA_FORMAT_ERR_MSG);
			return;
		}
		if(0 != mResp.getRetCode()){
			resp.setErrResp(Error.MALLSERVER_ERR_CD, mResp.getErrorMsg());
			return;
		}
		JSONObject result = mResp.getResult();
		JSONArray ret = new JSONArray();
		try{
			JSONArray statusList = result.getJSONArray("list");
			for(int index =0; index<statusList.length(); index++){
				JSONObject tmp = new JSONObject();
				JSONObject status = statusList.getJSONObject(index);
				tmp.put("DATE", status.getString("date"));
				tmp.put("SPRICE", status.getInt("localPrice"));
				tmp.put("STOCK", status.getInt("stockCount"));
				ret.put(tmp);
			}
			resp.appendRespContent("STATUSLIST", ret);
		}catch (JSONException e) {
			e.printStackTrace();
			resp.setErrResp(Error.SERVER_SYS_ERR_CD, Error.SERVER_SYS_ERR_MSG);
			return;
		}
	}

}
